import 'dart:convert';

import 'package:custom_refresh_indicator/custom_refresh_indicator.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:school_assistant/common_colors.dart';
import 'package:sp_util/sp_util.dart';

import 'common_client.dart';
import 'data/goods_entity.dart';
import 'data/order_extra_entity.dart';
import 'data/order_list_entity.dart';

class OrderList extends StatefulWidget {
  const OrderList({Key? key}) : super(key: key);

  @override
  State<OrderList> createState() => _OrderListState();
}

class _OrderListState extends State<OrderList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CommonColor.colorF5,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        title: Text(
          "我的订单",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: CustomRefreshIndicator(
        child: ListView.builder(
          itemBuilder: (cxt, index) {
            return _sinOrder(index);
          },
          itemCount: orders.length,
        ),
        builder: MaterialIndicatorDelegate(
          builder: (context, controller) {
            return Icon(
              Icons.ac_unit,
              color: Colors.blue,
              size: 30,
            );
          },
        ),
        onRefresh: myAsyncRefreshFunction,
      ),
    );
  }

  Future<void> myAsyncRefreshFunction() async {
    _getOrders();
  }

  _sinOrder(int index) {
    var order = orders[index];
    OrderExtraEntity? extra;
    if (order.extra?.isNotEmpty == true) {
      extra = OrderExtraEntity.fromJson(jsonDecode(order.extra ?? ''));
    }
    List<dynamic> data = jsonDecode(order.product ?? '');
    List<GoodsEntity> gs = [];
    if (data != null) {
      data.forEach((element) {
        gs.add(GoodsEntity.fromJson(element));
      });
    }
    return Container(
      margin: EdgeInsets.only(left: 12, right: 12, top: 12),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(5)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 12,
          ),
          Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
            SizedBox(
              width: 12,
            ),
            Text("订单号:",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 16,
                    fontWeight: FontWeight.w500)),
            Spacer(),
            Text(order.id ?? '', style: TextStyle(color: CommonColor.color33)),
            SizedBox(
              width: 12,
            ),
          ]),
          SizedBox(
            height: 10,
          ),
          Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
            SizedBox(
              width: 12,
            ),
            Text("下单时间:",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 16,
                    fontWeight: FontWeight.w500)),
            Spacer(),
            Text(extra?.time ?? '',
                style: TextStyle(color: CommonColor.color33)),
            SizedBox(
              width: 12,
            ),
          ]),
          SizedBox(
            height: 10,
          ),
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
            SizedBox(
              width: 12,
            ),
            Text("下单商品:",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 16,
                    fontWeight: FontWeight.w500)),
            SizedBox(
              width: 10,
            ),
            Expanded(
                child: RichText(
              textAlign: TextAlign.end,
              text: TextSpan(
                  children: gs
                      .map(
                        (e) => TextSpan(
                            text: (e.name ?? '') + "\n",
                            style: TextStyle(
                              color: CommonColor.color33,
                            )),
                      )
                      .toList()),
            )),
            SizedBox(
              width: 12,
            ),
          ]),
          SizedBox(
            height: 10,
          ),
          Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
            SizedBox(
              width: 12,
            ),
            Text("取单号:",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 16,
                    fontWeight: FontWeight.w500)),
            Spacer(),
            Text((extra?.code ?? '暂无'),
                style: TextStyle(color: CommonColor.color33)),
            SizedBox(
              width: 12,
            ),
          ]),
          SizedBox(
            height: 10,
          ),
          Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
            SizedBox(
              width: 12,
            ),
            Text("合计:",
                style: TextStyle(
                    color: CommonColor.color33,
                    fontSize: 16,
                    fontWeight: FontWeight.w500)),
            Spacer(),
            Text('¥' + (extra?.price ?? ''),
                style: TextStyle(color: CommonColor.color33)),
            SizedBox(
              width: 12,
            ),
          ]),
          SizedBox(
            height: 12,
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _getOrders();
  }

  List<OrderListEntity> orders = [];

  void _getOrders() async {
    try {
      var res = await CommonClient().getOrders(SpUtil.getString("uid") ?? "");
      List<dynamic> data = jsonDecode(res.data ?? '');
      List<OrderListEntity> gs = [];
      if (data != null) {
        data.forEach((element) {
          gs.add(OrderListEntity.fromJson(element));
        });
      }
      setState(() {
        orders.clear();
        orders.addAll(gs);
        orders.sort((a, b) {
          OrderExtraEntity? extraa, extrab;
          if (a.extra?.isNotEmpty == true) {
            extraa = OrderExtraEntity.fromJson(jsonDecode(a.extra ?? ''));
          }
          if (b.extra?.isNotEmpty == true) {
            extrab = OrderExtraEntity.fromJson(jsonDecode(b.extra ?? ''));
          }
          return (extrab?.time ?? '').compareTo(extraa?.time ?? "");
        });
      });
    } catch (e) {
      print(e);
    }
  }
}
